package com.traveldream.entity_managers;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.traveldream.entities.Booking;
import com.traveldream.entities.BookingPK;
import com.traveldream.entities.Packet;
import com.traveldream.entities.User;

/**
 * Session Bean implementation class BookingManagerBean
 */
@Stateless
public class BookingManagerBean implements BookingManager {
	
	// bisogna indicare che si usa la persistenza configurata nel package Common
	@PersistenceContext(unitName="TravelDreamCommon")
	EntityManager em;

	@Override
	public Booking create(Booking b) {
		// persist & flush em
 		em.persist(b);
		em.flush();
		em.refresh(b);
	    // return persisted object
        return b;
	}

	@Override
	public List<Booking> findByCustomer(User c) {
		Query query = em.createNamedQuery("Booking.findByCustomer",Booking.class).setParameter("customerEmail", c.getEmail());
    	List<Booking> results=new ArrayList<Booking>();
   		for( Object o : query.getResultList() ) 
   			results.add((Booking)o);
		return results;   
	}

	@Override
	public boolean delete(User c, Packet p) {
		//create key
		BookingPK key=new BookingPK();
		key.setCustomerEmail(c.getEmail());
		key.setPacketId(p.getId());
		//find by key
		Booking b=em.find(Booking.class,key);
		if( b!= null ) {
			em.remove(b);
			return true;
		}
		return false;
	}
	
	@Override
	public List<Booking> findAll() {
		Query query = em.createNamedQuery("Booking.findAll",Booking.class);
    	List<Booking> results=new ArrayList<Booking>();
   		for( Object o : query.getResultList() ) 
   			results.add((Booking)o);
		return results;   
	}
	
	public Booking find(BookingPK id){
		return em.find(Booking.class, id);
	}

}
